package com.yangtu.nearbyshop.core.corg.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.yangtu.nearbyshop.core.config.WxProperties;
import com.yangtu.nearbyshop.core.corg.Const;
import com.yangtu.nearbyshop.core.corg.CorgAdvance;
import com.yangtu.nearbyshop.core.corg.CorgChannel;
import com.yangtu.nearbyshop.core.corg.until.HttpClientUtils;
import com.yangtu.nearbyshop.core.corg.until.MD5SignUtil;
import com.yangtu.nearbyshop.core.corg.CorgMercChangeable;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.yangtu.nearbyshop.core.corg.Const.*;


/**
 * @author ZhangJinChang
 * @ClassName: CnlPayServiceImp
 * @Description: 向通道申请聚合支付服务类
 * @date 2018年08月10日 15:50
 */
@Service("CnlPayService")
public class CnlPayServiceImp implements CorgChannel,CorgMercChangeable,CorgAdvance {
    private Logger log= LoggerFactory.getLogger(this.getClass());

    /**
     * 通道服务请求url
     */
    private final static String hostPrefix = "https://gate.jingweitech.cn";
//    private final static String hostPrefix = "https://shopping.covsen.com";

    private final static String unionScanPayUrl = hostPrefix + "/v1/inteGration/jsApiReq";//聚合支付JSAPI

    private final static String setFzMercUrl = hostPrefix + "/v1/scanCode/fenzhangMercSet";//设置分账商户

    private final static String refundUrl = hostPrefix + "/v1/scanCode/aplRefund";//退款申请接口

    private final static String refundQueryUrl = hostPrefix + "/v1/scanCode/transaction/refundOrder";//退款查询接口
    @Autowired
    private WxProperties wxProperties;

    /**
     * 聚合支付接口（JSAPI接口）
     * @param context
     * @return
     * @throws Exception
     */
    public Map<String, String> inteGrationPay(Map<String, String> context) throws Exception {

        log.info("请求通道聚合支付的JSAPI聚合接口参数为{}" ,context);

        HashMap retMap = new HashMap();

        HashMap reqMap = new LinkedHashMap();
        reqMap.put("service", "SXFIntegrPay");
        reqMap.put("version", "1.0");
        reqMap.put("corgId", wxProperties.getOrgId());
        reqMap.put("dateTime", DateTime.now().toString("yyyyMMddHHmmss"));
        reqMap.put("orderNo", context.get("tranId"));
        reqMap.put("mercNo", wxProperties.getMchId());
        reqMap.put("notifyUrl", wxProperties.getNotifyUrl());
        reqMap.put("amount", new BigDecimal(context.get("txnAmt")).stripTrailingZeros().toPlainString());
        reqMap.put("prdNm", "购物消费");
        reqMap.put("payType", "WECHAT");
        reqMap.put("timerExpire", Const.CMM_EXPIRE_TIME);
        reqMap.put("limitPay", "00");
        reqMap.put("subOpenId", context.get("openid"));
        reqMap.put("subAppId", wxProperties.getAppId());
        if (StringUtils.isNotBlank(context.get("fenZhangJsonStr"))) {
            reqMap.put("fenZhangJsonStr", context.get("fenZhangJsonStr"));
        }

        String sign= MD5SignUtil.sign(reqMap,wxProperties.getMchKey());
        reqMap.put("signType", "md5");
        reqMap.put("sign", sign);

        log.info("【请求通道聚合支付的JSAPI聚合接口】执行步骤:[1]->请求的url={},请求参数{}" ,unionScanPayUrl, reqMap);
        String resultJson = HttpClientUtils.sendPostRequest(unionScanPayUrl, reqMap,"utf-8","utf-8");
        log.info("【请求通道聚合支付的JSAPI聚合接口】执行步骤:[2]->http返回结果{}" ,resultJson);

        if (StringUtils.isNotBlank(resultJson)) {
            Map<String, String> result= (Map<String, String>)JSONUtils.parse(resultJson);

            if("0000".equals(result.get(CMM_PARAM_RETURN_CODE))){
                retMap.put(CMM_PARAM_RETURN_CODE, Const.SUC_RETURN_CODE);
                retMap.put(Const.CMM_PARAM_RETURN_MSG, "处理成功");
                retMap.put("appId", result.get("appId"));
                retMap.put("timeStamp", result.get("timeStamp"));
                retMap.put("nonceStr", result.get("nonceStr"));
                retMap.put("packageValue", result.get("package"));
                retMap.put("signType", result.get("signType"));
                retMap.put("paySign", result.get("paySign"));
            }else {
                retMap.put(CMM_PARAM_RETURN_CODE, result.get(CMM_PARAM_RETURN_CODE));
                retMap.put(Const.CMM_PARAM_RETURN_MSG, result.get(Const.CMM_PARAM_RETURN_MSG));
            }
        }else {
            retMap.put(CMM_PARAM_RETURN_CODE, "0001");
            retMap.put(Const.CMM_PARAM_RETURN_MSG, "请求失败");
        }
        log.info("【请求通道聚合支付的JSAPI聚合接口】执行步骤:[3]->聚合支付返回上层结果{}" ,retMap);

        return retMap;
    }

    /**
     * 设置分账商户
     * @param mercNo
     * @return
     * @throws Exception
     */
    public Map<String, String> addFzMerclist(String mercNo){

        log.info("请求设置分账的商户号为{}" ,mercNo);

        HashMap retMap = new HashMap();

        HashMap reqMap = new LinkedHashMap();
        reqMap.put("service", "SXFIntegrPay");
        reqMap.put("version", "1.0");
        reqMap.put("corgId", wxProperties.getOrgId());
        reqMap.put("dateTime", DateTime.now().toString("yyyyMMddHHmmss"));
        reqMap.put("mercNo", wxProperties.getMchId());
        reqMap.put("excType", "1");
        JSONArray mercList = new JSONArray();
//        mercList.add(mercNo);
        mercList.put(mercNo);
        reqMap.put("mercListJsonStr", mercList.toString());
        String sign= MD5SignUtil.sign(reqMap,wxProperties.getMchKey());
        reqMap.put("signType", "md5");
        reqMap.put("sign", sign);

        log.info("【请求通道新增分账商户】执行步骤:[1]->请求的url={},请求参数{}" ,setFzMercUrl, reqMap);
        String resultJson = HttpClientUtils.sendPostRequest(setFzMercUrl, reqMap,"utf-8","utf-8");
        log.info("【请求通道新增分账商户】执行步骤:[2]->http返回结果{}" ,resultJson);

        if (StringUtils.isNotBlank(resultJson)) {
            Map<String, String> result= (Map<String, String>)JSONUtils.parse(resultJson);

            if("0000".equals(result.get(CMM_PARAM_RETURN_CODE))){
                retMap.put(CMM_PARAM_RETURN_CODE, Const.SUC_RETURN_CODE);
                retMap.put(Const.CMM_PARAM_RETURN_MSG, "处理成功");
            }else {
                retMap.put(CMM_PARAM_RETURN_CODE, result.get(CMM_PARAM_RETURN_CODE));
                retMap.put(Const.CMM_PARAM_RETURN_MSG, result.get(Const.CMM_PARAM_RETURN_MSG));
            }
        }else {
            retMap.put(CMM_PARAM_RETURN_CODE, "0001");
            retMap.put(Const.CMM_PARAM_RETURN_MSG, "请求失败");
        }
        log.info("【请求通道新增分账商户】执行步骤:[3]->聚合支付返回上层结果{}" ,retMap);

        return retMap;
    }

    /**
     * 退款申请接口
     * @param context
     * @return
     * @throws Exception
     */
    public Map<String, String> refundApply(Map<String, String> context) throws Exception {

        log.info("请求通道聚合支付的退款申请接口参数为{}" ,context);


        HashMap retMap = new HashMap();

        HashMap reqMap = new LinkedHashMap();
        reqMap.put("service", "SXFIntegrPay");
        reqMap.put("version", "1.0");
        reqMap.put("corgId", wxProperties.getOrgId());
        reqMap.put("dateTime", DateTime.now().toString("yyyyMMddHHmmss"));
        reqMap.put("orderNo", context.get("tranId"));//原退货订单编号
        reqMap.put("mercNo", wxProperties.getMchId());
        reqMap.put("amount", context.get("amount"));
        reqMap.put("reason", "用户退款");
        String sign= MD5SignUtil.sign(reqMap,wxProperties.getMchKey());
        reqMap.put("signType", "md5");
        reqMap.put("sign", sign);

        log.info("【请求通道聚合支付的退款申请】执行步骤:[1]->请求的url={},请求参数{}" ,refundUrl, reqMap);
        String resultJson = HttpClientUtils.sendPostRequest(refundUrl, reqMap,"utf-8","utf-8");
        log.info("【请求通道聚合支付的退款申请】执行步骤:[2]->http返回结果{}" ,resultJson);

        if (StringUtils.isNotBlank(resultJson)) {
            Map<String, String> result= (Map<String, String>)JSONUtils.parse(resultJson);

            if("0000".equals(result.get(CMM_PARAM_RETURN_CODE))){
                retMap.put(CMM_PARAM_RETURN_CODE, SUC_RETURN_CODE);
                retMap.put(CMM_PARAM_RETURN_MSG, "处理成功");
                retMap.put(UP_CORG_TRAN_ID, result.get("refundId"));

            }else {
                retMap.put(CMM_PARAM_RETURN_CODE, result.get(CMM_PARAM_RETURN_CODE));
                retMap.put(CMM_PARAM_RETURN_MSG, result.get(CMM_PARAM_RETURN_MSG));
            }
        }else {
            retMap.put(CMM_PARAM_RETURN_CODE, "0001");
            retMap.put(CMM_PARAM_RETURN_MSG, "请求失败");
        }
        log.info("【请求通道聚合支付的退款申请】执行步骤:[3]->聚合支付返回上层结果{}" ,retMap);

        return retMap;
    }

    /**
     * 退款结果查询接口
     * @param context
     * @return
     * @throws Exception
     */
    public Map<String, String> refundQry(Map<String, String> context) throws Exception {

        log.info("请求通道聚合支付的退款查询接口参数为{}" ,context);


        HashMap retMap = new HashMap();

        HashMap reqMap = new LinkedHashMap();
        reqMap.put("service", "SXFIntegrPay");
        reqMap.put("version", "1.0");
        reqMap.put("corgId", wxProperties.getOrgId());
        reqMap.put("dateTime", DateTime.now().toString("yyyyMMddHHmmss"));
        reqMap.put("orderNo", context.get("refundId"));//受理的退款订单号RF开头
        reqMap.put("mercNo", wxProperties.getMchId());
        String sign= MD5SignUtil.sign(reqMap,wxProperties.getMchKey());
        reqMap.put("signType", "md5");
        reqMap.put("sign", sign);

        log.info("【请求通道聚合支付的退款查询】执行步骤:[1]->请求的url={},请求参数{}" ,refundQueryUrl, reqMap);
        String resultJson = HttpClientUtils.sendPostRequest(refundQueryUrl, reqMap,"utf-8","utf-8");
        log.info("【请求通道聚合支付的退款查询】执行步骤:[2]->http返回结果{}" ,resultJson);

        if (StringUtils.isNotBlank(resultJson)) {
            Map<String, String> result= (Map<String, String>)JSONUtils.parse(resultJson);

            if("0000".equals(result.get(CMM_PARAM_RETURN_CODE))){
                retMap.put(CMM_PARAM_RETURN_CODE, SUC_RETURN_CODE);
                retMap.put(CMM_PARAM_RETURN_MSG, "处理成功");
                retMap.put("refundSts", result.get("paySts"));
            }else {
                retMap.put(CMM_PARAM_RETURN_CODE, result.get(CMM_PARAM_RETURN_CODE));
                retMap.put(CMM_PARAM_RETURN_MSG, result.get(CMM_PARAM_RETURN_MSG));
            }
        }else {
            retMap.put(CMM_PARAM_RETURN_CODE, "0001");
            retMap.put(CMM_PARAM_RETURN_MSG, "请求失败");
        }
        log.info("【请求通道聚合支付的退款申请】执行步骤:[3]->聚合支付返回上层结果{}" ,retMap);

        return retMap;
    }
}
